package member.controller;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import member.domain.Member;
import member.model.service.MemberService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/member/")
// class에 지정한 URL - 모든 Handler 메소드들의 URL 앞에 붙이는 공통 경로 지정
public class MemberController {
	@Autowired
	private MemberService service;

	// 로그인
	// 로그인 form을 제공
	@RequestMapping(value = "login.do", method = RequestMethod.GET)
	public String loginForm() {
		return "member/login_form.jsp";// View Name 리턴
	}

	// 로그인 처리
	@RequestMapping(value = "login.do", method = RequestMethod.POST)
	public String login(String id, String password, HttpSession session,
			ModelMap map) throws Exception {

		// 비지니스 로직 - Model 호출(Bussiness Service)

		Member member = service.getMemberById(id);
		String url = null;

		if (member != null) {
			// 로그인 성공 - session - attribute(login_info, 로그인한 회원 정보)
			if (password.equals(member.getPassword())) {
				session.setAttribute("login_info", member);

				// 성공 : view - main.jsp
				url = "main.jsp";

			}

			else {// pwd가 틀린경우
				url = "member/login_form.jsp";
				map.addAttribute("error_message", "비밀번호가 틀렸습니다.");
			}

		} else {// id 가 틀린경우
			url = "member/login_form.jsp";
			map.addAttribute("error_message", "ID가 틀렸습니다.");
		}

		return url;
	}

	@RequestMapping(value = "logout.do", method = RequestMethod.GET)
	public String logout(HttpSession session) {

		// 세션을 소멸 -> main.jsp
		session.invalidate();
		return "main.jsp";
	}

	/**************** 가입처리 ***************/
	// 가입 폼
	@RequestMapping(value = "join.do", method = RequestMethod.GET)
	public String joinForm() {
		return "member/join_form.jsp";
	}

	// 가입 처리
	@RequestMapping(value = "join.do", method = RequestMethod.POST)
	public String joinMember(Member member) throws Exception {
		service.joinMember(member);
		// join_success.jsp
		return "member/join_success.jsp";
	}

	// 전체 회원 목록 조회
	@RequestMapping("memberList.do")
	public ModelAndView memberList() throws Exception {
		List<Member> list = service.getMemberList();
		return new ModelAndView("member/member_list.jsp", "member_list", list);
	}
	
	// 회원 정보 조회
	@RequestMapping("login/getMemberInfo.do")
	public String getMemberInfo(HttpSession session, ModelMap map) {
		String url = null;
		
		if(session.getAttribute("login_info") != null){
			
			url = "member/member_info.jsp";
			
		}
		else {
			url = "member/login_form.jsp";
			map.addAttribute("error_message", "세션이 만료되었습니다. 다시 로그인하세요.");
		}
 		// 로그인 체크 - O -> member_info.jsp
		//			   - X -> login_form.jsp (attribute : 메세지)
	
			return url;
	}
	
	// 수정 폼
	@RequestMapping(value="login/modify.do", method=RequestMethod.GET)
	public String modifyForm(HttpSession session, ModelMap map){
		String url = null;
		if(session.getAttribute("login_info") != null) {
			url = "member/modify_form.jsp";
		}else {
			url = "member/login_form.jsp";
			map.addAttribute("error_message", "로그인이 필요합니다.");
		}
		
		return url;
	
	}
	
	// 수정 처리
	@RequestMapping(value="login/modify.do", method=RequestMethod.POST)
	public String modifyMemberInfo(HttpSession session, Member member, ModelMap map) throws SQLException {
		//로그인 여부 체크
		String url = null;
		//로그인 상태라면
		Member sessionMember = (Member) session.getAttribute("login_info");
		if(sessionMember!= null) {
			
			//비지니스 로직 - service.modifyMember(수정할 정보)
			//Session의 회원정보 수정
					member.setJoinDate(sessionMember.getJoinDate());
					service.modifyMember(member);
			
					session.setAttribute("login_info", member);
					//응답처리 : member_info.jsp
					url = "member/member_info.jsp";
		}
		
		else {
			url = "member/login_form.jsp";
			map.addAttribute("error_message", "로그인이 필요합니다.");
		}
		
		return url;
	}
	
	// 탈퇴
	@RequestMapping(value="login/remove.do")
	public String removeMember(HttpSession session) throws SQLException {
		String url = null;
		//로그인 확인 O 
		Member member = (Member) session.getAttribute("login_info");
		if(member != null) {
			//회원 정보 삭제 - removeMemberById(id)
			service.removeMemberById(member.getId());
			//로그아웃 처리 (정보를 지우고 세션정보도 지워야함)
			session.invalidate();
			
			//응답 : main.jsp
			url = "main.jsp";
		}
		return url;
		
	}
	//전체목록 조회 - 페이징 처리
	@RequestMapping("memberListPaging.do")
	public ModelAndView memberListPaging(@RequestParam(defaultValue="1") int page) throws SQLException {
		Map map = service.getMemberListPaging(page);
		//member_list_paging.jsp
		return new ModelAndView("member/member_list_paging.jsp", map);
		
		
	}
	
	@RequestMapping("searchForm.do")
	public String searchForm(){
		return "member/ajax_search.jsp";
	}
	
	@RequestMapping("searchMemberById.do")
	public String searchMemberById(String id, ModelMap map) throws SQLException{
		Member member = service.getMemberById(id);
		map.addAttribute("member", member); //Model
		// {member:{id:"id-1", name:"김철수"}} -> mappingJackson2jason 을 불렀을때! 저렇게 만들어줌
		
		return "jsonView"; //View Name - MappingJackson2JasonView
	
	}
	
}
